﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Interface;

namespace Model
{
    public class ClsPumpestation
    {
        public List<ClsKanal> Kanaler { get; private set; }
        ClsKanalCol KanalCol;
        ClsPumpeCol PumpeCol;
        IClsController C;

        public ClsPumpestation(int Nr, ClsKanalCol KanalCol, ClsPumpeCol PumpeCol)
        {
            ChannelFactory<IClsController> F = new ChannelFactory<IClsController>(new NetTcpBinding(), "net.tcp://localhost:" + Nr + "/");
            this.C = F.CreateChannel();
            this.KanalCol = KanalCol;
            this.PumpeCol = PumpeCol;
            this.Kanaler = new List<ClsKanal>();

            HentKanaler();
            HentP();
        }

        private void HentKanaler()
        {
            ClsKanal Kanal;
            foreach (Kanal K in this.C.HentKanaler())
            {
                Kanal = this.KanalCol.Kanaler.SingleOrDefault(val => val.Id == K.Id);

                if (Kanal == null)
                    Kanal = this.KanalCol.TilføjKanal(K.Id, K.kapacitet);

                Kanal.Vandstand = 0;
                this.Kanaler.Add(Kanal);
            }
        }

        private void HentP()
        {
            ClsPumpe Pum;
                foreach (Pumpe P in this.C.HentPumper())
                {
                    Pum = this.PumpeCol.Pumper.SingleOrDefault(val => val.Id == P.Id);

                    if (Pum == null)
                    {
                        Pum = new ClsPumpe(P.Id, P.KvadratmeterVandSekundet);

                        this.PumpeCol.TilføjPumpe(Pum);
                        this.KanalCol.Kanaler
                            .Single(val => val.Id == P.FraId)
                            .TilføjFraPumpe(Pum);

                        this.KanalCol.Kanaler
                            .Single(val => val.Id == P.TilId)
                            .TilføjTilPumpe(Pum);
                    }
                }
        }

        public void SendVandstand(int KanalId)
        {
            ClsKanal K = this.Kanaler.SingleOrDefault(val => val.Id == KanalId);

            if (K != null)
            {
                try
                {
                    C.SetVandstand(K.Id, K.BeregnVandstand(), DateTime.Now);
                }
                catch
                { 
                    //...
                }
            }
        }
    }
}
